import { login, userProfile, getUserDetailById } from '@/api/user'
import { getToken, setToken } from '@/utils/auth'

export default {
  namespaced: true,
  state: () => {
    return {
      // 保存token
      token: getToken() || '',
      userInfo: {}
    }
  },
  mutations: {
    // 设置token
    setToken(state, newToken) {
      state.token = newToken

      // 调用封装好的函数,本地储存token
      setToken(newToken)
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
    }
  },
  actions: {
    // data 用户和密码
    async userLogin(context, data) {
      const res = await login(data)
      context.commit('setToken', res.data)
    },
    // 获取用户信息
    async getUserProfile(context) {
      const res = await userProfile()
      const reLogin = await getUserDetailById(res.data.userId)
      context.commit('setUserInfo', { ...res.data, ...reLogin.data })
    },
    logout(context) {
      // 清空token
      context.commit('setToken', '')
      // 清空用户信息
      context.commit('setUserInfo', {})
    }
  },
  getters: {}
}
